package com.xy.tool.concurrent.locks.local;

import com.xy.lang.util.UuidUtils;
import com.xy.tool.concurrent.locks.DisLock;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

public class LocalDisLock implements DisLock {

    private LocalDisLockFactory localDisLockFactory;
    private String id;

    public LocalDisLock(LocalDisLockFactory localDisLockFactory) {
        Objects.requireNonNull(localDisLockFactory);
        this.localDisLockFactory = localDisLockFactory;
        this.id = UuidUtils.compactSystemUuid();
    }

    @Override
    public boolean lock(String resource) {
        LockWrapper lockWrapper = localDisLockFactory.getOrCreateLock(resource);
        boolean flag = lockWrapper.getLock().tryLock();
        if(flag) {
            lockWrapper.setId(id);
        }
        return flag;
    }

    @Override
    public boolean lock(String resource, long timeoutMillis) {
        LockWrapper lockWrapper = localDisLockFactory.getOrCreateLock(resource);
        try {
            boolean flag = lockWrapper.getLock().tryLock(timeoutMillis, TimeUnit.MILLISECONDS);
            if(flag) {
                lockWrapper.setId(id);
            }
            return flag;
        } catch (InterruptedException e) {
            return false;
        }
    }

    @Override
    public boolean unlock(String resource) {
        LockWrapper lockWrapper = localDisLockFactory.get(resource);
        if(lockWrapper == null) {
            return true;
        }
        if(id.equals(lockWrapper.getId())) {
            lockWrapper.getLock().unlock();
            return true;
        }
        return false;
    }

}
